package com.dwin.h5.app.ui;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.dwin.h5.app.H5Application;
import com.dwin.h5.app.R;
import com.dwin.h5.app.models.TabItem;
import com.dwin.h5.app.models.WeatherModel;
import com.dwin.h5.app.models.response.HomeTabRsp;
import com.dwin.h5.app.ui.fragments.BaseH5Fragment;
import com.dwin.h5.app.utils.Constants;
import com.dwin.h5.app.utils.LocalManageUtil;
import com.dwin.h5.app.utils.ToastUtil;
import com.dwin.h5.app.utils.http.UserManageRetrofit;
import com.dwin.h5.app.utils.http.WeatherRetrofit;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Response;

/**
 * 混合开发，主页面（包含n个webView形式的tab）
 */
public class MainActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";

    private FrameLayout fragment_container;
    private Handler handler = new Handler();//用来控制底部bottom 点击频率
    private View view_btm_line;
    private LinearLayout bottom_bar;
    private boolean isSinglePage = false; // 是否只有一个tab

    private RelativeLayout rl_tab01, rl_tab02, rl_tab03, rl_tab04, rl_tab05;
    private ImageView iv_tab01, iv_tab02, iv_tab03, iv_tab04, iv_tab05;
    private TextView tv_tab01, tv_tab02, tv_tab03, tv_tab04, tv_tab05;

    private List<TabItem> tabs; //
    private int currentTabIndex = PAGE_01;
    private static final int PAGE_01 = 1;
    private static final int PAGE_02 = 2;
    private static final int PAGE_03 = 3;
    private static final int PAGE_04 = 4;
    private static final int PAGE_05 = 5;

    private Fragment cFragment;
    private Fragment mFragment01;
    private Fragment mFragment02;
    private Fragment mFragment03;
    private Fragment mFragment04;
    private Fragment mFragment05;
    private List<Fragment> fragments = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "onCreate====:" + System.currentTimeMillis());
        getTabsInfo(); // 获取tab信息

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                initViews(); // 页面子元素初始化，延时执行
                initFragment();
                Log.d(TAG, "handler finished:" + System.currentTimeMillis());

                if (hasPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
                    doCoarseLocation();
                } else {
                    requestPermissions(Constants.COARSE_LOCATION_CODE,
                            android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION);
                }
            }
        }, 50);
    }

    LocationManager locationManager;
    TestLocationListener locationListener = new TestLocationListener();

    @Override
    public void doCoarseLocation() {
        locationManager = (LocationManager) MainActivity.this.getSystemService(Context.LOCATION_SERVICE);
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
        }
    }

    // 定位获取经纬度，监听
    private class TestLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            String msg = "onLocationChanged:latitude-> " + location.getLatitude() + " Longtitude-> " + location.getLongitude();
            // 位置发生改变时，调用这个方法
            getCityInfo(location.getLatitude(), location.getLongitude());
            locationManager.removeUpdates(locationListener);
        }

        @Override
        public void onProviderDisabled(String arg0) {
        }

        @Override
        public void onProviderEnabled(String arg0) {
        }

        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        }
    }

    // 根据经纬度，获取城市名称信息
    private void getCityInfo(final double lat, final double Lng) {
        WeatherRetrofit.getInstance().getLocInfo(lat + "," + Lng, new retrofit2.Callback<WeatherModel>() {
            @Override
            public void onResponse(retrofit2.Call<WeatherModel> call, Response<WeatherModel> response) {
                if ("OK".equals(response.body().status)) {
                    // 验证码发送完成
                    H5Application.addressComponent = response.body().result.addressComponent;
                    H5Application.lat = lat;
                    H5Application.lng = Lng;
//                    H5Application.province = addressComponent.province;
//                    H5Application.city = addressComponent.city;
                }
            }

            @Override
            public void onFailure(retrofit2.Call<WeatherModel> call, Throwable t) {
                Log.d(TAG, "onFailure: ");
            }
        });
    }

    private void initFragment() {
        if (tabs != null && tabs.size() > 0) { // 只有一个item
            mFragment01 = new BaseH5Fragment();
            ((BaseH5Fragment) mFragment01).setPageUrl(tabs.get(0).url);
            fragments.add(mFragment01);
            currentTabIndex = PAGE_01;

            if (tabs.size() >= 2) {
                mFragment02 = new BaseH5Fragment();
                ((BaseH5Fragment) mFragment02).setPageUrl(tabs.get(1).url);
                fragments.add(mFragment02);
                if (tabs.size() >= 3) {
                    mFragment03 = new BaseH5Fragment();
                    ((BaseH5Fragment) mFragment03).setPageUrl(tabs.get(2).url);
                    fragments.add(mFragment03);
                    if (tabs.size() >= 4) {
                        mFragment04 = new BaseH5Fragment();
                        ((BaseH5Fragment) mFragment04).setPageUrl(tabs.get(3).url);
                        fragments.add(mFragment04);
                        if (tabs.size() >= 5) {
                            mFragment05 = new BaseH5Fragment();
                            ((BaseH5Fragment) mFragment05).setPageUrl(tabs.get(4).url);
                            fragments.add(mFragment05);
                        }// tab >=5个item
                    } // tab >=4个item
                } // tab >=3个item
            }// tab>=2个item
        }
        if (fragments.isEmpty() == false) {
            switchFragment();
        }
    }

    // 其他tab点击， home主页面需要切换tab。
    public void selectTab(String tabName) {
        if ("tab2".equals(tabName)){
            currentTabIndex = PAGE_02; // 切换显示
        } else if ("tab3".equals(tabName)){
            currentTabIndex = PAGE_03; // 切换显示
        } else if ("tab4".equals(tabName)){
            currentTabIndex = PAGE_04; // 切换显示
        }else if ("tab5".equals(tabName)){
            currentTabIndex = PAGE_05; // 切换显示
        } else {
            currentTabIndex = PAGE_01;
        }
        updateIconsAndTextColor();
        switchFragment();
    }


    private synchronized void switchFragment() {
        bottom_bar.setEnabled(false);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                bottom_bar.setEnabled(true);
            }
        }, 2000);
        Fragment fragment = fragments.get(currentTabIndex - 1);
        FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();
        if (cFragment == null && !fragment.isAdded()) {
            beginTransaction.add(R.id.fragment_container, fragment, currentTabIndex + "");
        } else if (fragment.isAdded()) {
            beginTransaction.hide(cFragment).show(fragment);
        } else {
            beginTransaction.hide(cFragment).add(R.id.fragment_container, fragment);
        }
        cFragment = fragment;
        beginTransaction.commitAllowingStateLoss();
        Log.d(TAG, "switchFragment======: " + System.currentTimeMillis());
    }

    @Override
    public void initViews() {
        Log.d("H5", "MainActivity--initViews");
        fragment_container = findViewById(R.id.fragment_container); // 上部大的容器
        view_btm_line = findViewById(R.id.view_btm_line); // tab栏目上线条
        bottom_bar = findViewById(R.id.bottom_bar); // tab容器

        rl_tab01 = findViewById(R.id.rl_tab01);
        rl_tab02 = findViewById(R.id.rl_tab02);
        rl_tab03 = findViewById(R.id.rl_tab03);
        rl_tab04 = findViewById(R.id.rl_tab04);
        rl_tab05 = findViewById(R.id.rl_tab05);
        rl_tab01.setOnClickListener(this);
        rl_tab02.setOnClickListener(this);
        rl_tab03.setOnClickListener(this);
        rl_tab04.setOnClickListener(this);
        rl_tab05.setOnClickListener(this);

        iv_tab01 = findViewById(R.id.iv_tab01);
        iv_tab02 = findViewById(R.id.iv_tab02);
        iv_tab03 = findViewById(R.id.iv_tab03);
        iv_tab04 = findViewById(R.id.iv_tab04);
        iv_tab05 = findViewById(R.id.iv_tab05);
        tv_tab01 = findViewById(R.id.tv_tab01);
        tv_tab02 = findViewById(R.id.tv_tab02);
        tv_tab03 = findViewById(R.id.tv_tab03);
        tv_tab04 = findViewById(R.id.tv_tab04);
        tv_tab05 = findViewById(R.id.tv_tab05);

        tabs = LitePal.findAll(TabItem.class);
        if (tabs.isEmpty() || tabs.size() <= 1) { // 只有一个item
            view_btm_line.setVisibility(View.GONE); // tab栏目上线条
            bottom_bar.setVisibility(View.GONE);
            isSinglePage = true;
        } else {
            isSinglePage = false;
            view_btm_line.setVisibility(View.VISIBLE); // tab栏目上线条
            bottom_bar.setVisibility(View.VISIBLE);
            if (tabs.size() >= 2) {
                rl_tab01.setVisibility(View.VISIBLE);
                rl_tab02.setVisibility(View.VISIBLE);
                tv_tab01.setText(tabs.get(0).tab_text);
                tv_tab02.setText(tabs.get(1).tab_text);
                Glide.with(this).load(tabs.get(0).tab_image_on).into(iv_tab01);
                Glide.with(this).load(tabs.get(1).tab_image_off).into(iv_tab02);
                if (tabs.size() >= 3) {
                    rl_tab03.setVisibility(View.VISIBLE);
                    tv_tab03.setText(tabs.get(2).tab_text);
                    Glide.with(this).load(tabs.get(2).tab_image_off).into(iv_tab03);
                    if (tabs.size() >= 4) {
                        rl_tab04.setVisibility(View.VISIBLE);
                        tv_tab04.setText(tabs.get(3).tab_text);
                        Glide.with(this).load(tabs.get(3).tab_image_off).into(iv_tab04);
                        if (tabs.size() >= 5) {
                            rl_tab05.setVisibility(View.VISIBLE);
                            tv_tab05.setText(tabs.get(4).tab_text);
                            Glide.with(this).load(tabs.get(4).tab_image_off).into(iv_tab05);
                        } // tab >=5个item
                    } // tab >=4个item
                } // tab >=3个item
            } // tab>=2个item
        } // 存在2个以上item
    }

    private void getTabsInfo() {
        if (!isNetworkConnected(mContext)) {
            ToastUtil.toastShort(mContext, R.string.net_error);
            return;
        }
        String language = LocalManageUtil.getSystemLocaleLng(mContext);
        UserManageRetrofit.getInstance().getHomeTabs(language, new retrofit2.Callback<HomeTabRsp>() {
            @Override
            public void onResponse(retrofit2.Call<HomeTabRsp> call, Response<HomeTabRsp> response) {
                if (Constants.HTTP_OK == response.body().code) {
                    logMessage.edit().putString("loginUrl", response.body().data.login_url).commit();
                    logMessage.edit().putString("version", response.body().data.version).commit();
                    Log.d(TAG, "onResponse: " + response.body().data.tabs.toString());
                    ArrayList<TabItem> tabs = response.body().data.tabs;
                    LitePal.deleteAll(TabItem.class); // clear saved data
                    for (int i = 0; i < tabs.size(); i++) {
                        tabs.get(i).save();
                    }
                    findAllData();

                    Log.d(TAG, "getTabsInfo finished:" + System.currentTimeMillis());
                }
            }

            @Override
            public void onFailure(retrofit2.Call<HomeTabRsp> call, Throwable t) {
                Log.d(TAG, "onFailure: ");
            }
        });
    }

    private void findAllData() {
        List<TabItem> list = LitePal.findAll(TabItem.class);
        for (TabItem tabItem : list) {
            Log.d(TAG, tabItem.toString());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_tab01: // currentTabIndex =1
                if (currentTabIndex == PAGE_01) {
                    ((BaseH5Fragment)mFragment01).reLoadPage();
                    return;
                }
                currentTabIndex = PAGE_01;
                break;
            case R.id.rl_tab02:
                if (currentTabIndex == PAGE_02) {
                    ((BaseH5Fragment)mFragment02).reLoadPage();
                    return;
                }
                currentTabIndex = PAGE_02;
                break;
            case R.id.rl_tab03:
                if (currentTabIndex == PAGE_03) {
                    ((BaseH5Fragment)mFragment03).reLoadPage();
                    return;
                }
                currentTabIndex = PAGE_03;
                break;
            case R.id.rl_tab04:
                if (currentTabIndex == PAGE_04) {
                    ((BaseH5Fragment)mFragment04).reLoadPage();
                    return;
                }
                currentTabIndex = PAGE_04;
                break;
            case R.id.rl_tab05:
                if (currentTabIndex == PAGE_05) {
                    ((BaseH5Fragment)mFragment05).reLoadPage();
                    return;
                }
                currentTabIndex = PAGE_05;
                break;
        }
        updateIconsAndTextColor();  // updateTabIcons
        switchFragment(); // 切换显示Fragment
    }

    // tab大于2个，底部tab切换刷新
    private void updateIconsAndTextColor() {
        if (tabs.size() >= 2) {
            tv_tab01.setTextColor(getResources().getColor(R.color.color_tab_off));
            tv_tab02.setTextColor(getResources().getColor(R.color.color_tab_off));
            Glide.with(this).load(tabs.get(0).tab_image_off).into(iv_tab01);
            Glide.with(this).load(tabs.get(1).tab_image_off).into(iv_tab02);
            if (tabs.size() >= 3) {
                tv_tab03.setTextColor(getResources().getColor(R.color.color_tab_off));
                Glide.with(this).load(tabs.get(2).tab_image_off).into(iv_tab03);
                if (tabs.size() >= 4) {
                    tv_tab04.setTextColor(getResources().getColor(R.color.color_tab_off));
                    Glide.with(this).load(tabs.get(3).tab_image_off).into(iv_tab04);
                    if (tabs.size() >= 5) {
                        tv_tab05.setTextColor(getResources().getColor(R.color.color_tab_off));
                        Glide.with(this).load(tabs.get(4).tab_image_off).into(iv_tab05);
                    } // tab >=5个item
                } // tab >=4个item
            } // tab >=3个item
        } // tab>=2个item
        switch (currentTabIndex) {
            case PAGE_01:
                tv_tab01.setTextColor(getResources().getColor(R.color.color_tab_on));
                Glide.with(this).load(tabs.get(0).tab_image_on).into(iv_tab01);
                break;
            case PAGE_02:
                tv_tab02.setTextColor(getResources().getColor(R.color.color_tab_on));
                Glide.with(this).load(tabs.get(1).tab_image_on).into(iv_tab02);
                break;
            case PAGE_03:
                tv_tab03.setTextColor(getResources().getColor(R.color.color_tab_on));
                Glide.with(this).load(tabs.get(2).tab_image_on).into(iv_tab03);
                break;
            case PAGE_04:
                tv_tab04.setTextColor(getResources().getColor(R.color.color_tab_on));
                Glide.with(this).load(tabs.get(3).tab_image_on).into(iv_tab04);
                break;
            case PAGE_05:
                tv_tab05.setTextColor(getResources().getColor(R.color.color_tab_on));
                Glide.with(this).load(tabs.get(4).tab_image_on).into(iv_tab05);
                break;
        }
    }

    // 隐藏底部tab栏
    public void setTabsVisiable(String command) {
        if (isSinglePage) { // 页面中只有一个Tab，隐藏底部的tab栏
            view_btm_line.setVisibility(View.GONE);
            bottom_bar.setVisibility(View.GONE);
        } else { // 页面有2个及以上tab，控制显示或隐藏tab栏
            if ("hide".equals(command)) {
                view_btm_line.setVisibility(View.GONE);
                bottom_bar.setVisibility(View.GONE);
            } else {
                view_btm_line.setVisibility(View.VISIBLE);
                bottom_bar.setVisibility(View.VISIBLE);
            }
        }
    }

    private long firstClickBackTime = 0; // 第一次点击back键的时间

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        long secondTime = System.currentTimeMillis();
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (cFragment != null) {
                if (((BaseH5Fragment)cFragment).webViewGoBack()) {
                    return true;
                }
            }

            if (secondTime - firstClickBackTime < 2000) {
                System.exit(0);
            } else {
                Toast.makeText(MainActivity.this, R.string.press_again_2exit, Toast.LENGTH_SHORT).show();
                firstClickBackTime = System.currentTimeMillis();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
